package utils

import (
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"math/rand"
	"strconv"
	"time"
	"tizhi_front/nspel"
)

type Phone struct {
	Phone string
}

func (p *Phone) ValidCode(validCode string, typeI int) (ok bool, err error) {
	ok, err = nspel.RedisIsExist("phone:" + p.Phone + ".type:" + strconv.Itoa(typeI) + ".valid_code:" + validCode)
	return
}

func (p *Phone) ValidIsActive(typeI int) (ok bool, err error) {
	ok, err = nspel.RedisIsExist("phone:" + p.Phone + ".type:" + strconv.Itoa(typeI) + ".active")
	return
}

func (p *Phone) SendSms(Type int) (err error) {
	validCode := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Scheme = "https"
	request.Domain = "dysmsapi.aliyuncs.com"
	request.Version = "2017-05-25"
	request.ApiName = "SendSms"
	request.QueryParams["RegionId"] = "cn-hangzhou"
	request.QueryParams["PhoneNumbers"] = p.Phone
	request.QueryParams["SignName"] = nspel.GetSignName()
	request.QueryParams["TemplateCode"] = nspel.GetTemplateMsm(Type)
	request.QueryParams["TemplateParam"] = "{\"code\":\"" + validCode + "\"}"
	// nspel.Error(request.QueryParams)
	_, err = nspel.GetSmsClient().ProcessCommonRequest(request)
	if err != nil {
		err = nspel.ReconnectSms()
		if err != nil {
			return
		}
		_, err = nspel.GetSmsClient().ProcessCommonRequest(request)
		if err != nil {
			return
		}
	}
	err = nspel.RedisSet("phone:"+p.Phone+".type:"+strconv.Itoa(Type)+".active", true, 60)
	if err != nil {
		return
	}
	err = nspel.RedisSet("phone:"+p.Phone+".type:"+strconv.Itoa(Type)+".valid_code:"+validCode, true, 300)
	if err != nil {
		return
	}
	return
}
